<?php
/**
 *
 * @author Quentin Laujac, Charles Hurtevent
 *
 */
require_once ("../enums/enums.php");
require_once ("../bean/data/Article.php");
require_once ("../bean/data/Commande.php");
require_once ("../bean/data/Facture.php");
require_once ("../bean/data/Utilisateur.php");
require_once ("../services/ClientService.php");

// si le formulaire est envoye
if($_POST['submitCommande'] != null) {
	session_start();
	//creation des objets
	$clientService = new ClientService();
	$commande = new Commande();
	$listArticleCommande = new ArrayObject();
	$facture = new Facture();
	$date = new DateTime();
	$dateCommande = $date->format('Y-m-d H:i:s');
	$client = $_SESSION['login'];
	$listLieu = $_SESSION ['listLieu'];


	//recuperation des articles choisi
	foreach ( $_SESSION['listArticle'] as $article ) {
		$article->setQuantiteCommandee($_POST['quantite'.$article->getNumArticle()]);
		$listArticleCommande->append($article);
	}

	//Recuperation du lieu choisi
	foreach($listLieu as $lieu){
		if($lieu->getNumeroLieu() == $_POST["Lieu"]){
			$lieuChoisi = $lieu;
			break;
		}
	}

	//set la commande
	$commande->setNumeroCommande($_SESSION['numCommande']);
	$commande->setClient($_SESSION['login']);
	$commande->setDateCommande($dateCommande);
	$commande->setEstValide($_POST['submitCommande'] == "Valider");
	$commande->setFacture($facture);
	$commande->setLieuLivraison($lieuChoisi);
	$commande->setListArticle($listArticleCommande);

	echo $commande->getNumeroCommande();
	echo $commande->getClient()->getNom();
	echo $commande->getDateCommande();
	echo $commande->isValide();
	echo $commande->getLieuLivraison()->getAdresse();
	$listArticle = $commande->getListArticle();

	echo"<br/>";
	foreach($listArticleCommande as $article){
		echo $article->getLibelle();
		echo " Quantite :".$article->getQuantiteCommandee();
		echo"<br/>";
	}


	$etat = $clientService->miseAJourCommande($commande);
	if($etat == null){
		//On remet a jour la liste des commandes
		$client = $_SESSION ['login'];
		$listCommande = $clientService->getHistoriqueCommande ( $client );
		$_SESSION ['listCommande'] = $listCommande;

		//Fermeture de la page
		echo "<script language='javascript'>javascript:parent.opener.location.reload();</script>";
		echo "<script language='javascript'>window.close()</script>";
		exit();
	}

	//erreur enregistrement commande
	$_SESSION ['messageErreur'] = $etat;
	echo "<script language='javascript'>javascript:parent.opener.location.reload();</script>";
	header ( 'Location: ../web/popUp_editer_commande.php' );
	exit ();
}
